function Cart(){
	var cookieName = "cart";
	var items;
	
	Cart.prototype.getItems = function(){
		return items;
	}
	
	Cart.prototype.addToCart = function(id, title, price){
		var itemFound = null;
		for(var i=0;i<items.length;i++){
			if(items[i].id == id){
				itemFound = items[i];
				break;
			}
		}
		if(itemFound){
			itemFound.quantity++;
		}else{
			var item = {"id":id, "title":title, "price":price, "quantity":1};
			items.push(item);
		}
		
		this.save();
		msgBox.alert("消息", "书籍【" + title + "】添加成功！")
	}
	
	Cart.prototype.removeFromCart = function(id){
		for(var i=0;i<items.length;i++){
			if(items[i].id == id){
				break;
			}
		}
		items.splice(i, 1);
		this.save();
	}
	
	Cart.prototype.increaseNum = function(id){
		for(var i=0;i<items.length;i++){
			if(items[i].id == id){
				items[i].quantity++;
				break;
			}
		}
		this.save();
	}
	
	Cart.prototype.decreaseNum = function(id){
		for(var i=0;i<items.length;i++){
			if(items[i].id == id){
				items[i].quantity--;
				if(items[i].quantity == 0){
					items.splice(i, 1);
				}
				break;
			}
		}
		this.save();
	}
	
	Cart.prototype.sum = function(){
		var total = 0.0;
		for(var i=0;i<items.length;i++){
			total += items[i].price * items[i].quantity;
		}
		return total.toFixed(2);
	}
	
	Cart.prototype.count = function(){
		var count = 0;
		for(var i=0;i<items.length;i++){
			count += items[i].quantity;
		}
		return count;
	}
	
	Cart.prototype.save = function(){
		var itemsStr = JSON.stringify(items);
		setCookie(cookieName, itemsStr);
	}
	
	Cart.prototype.load = function(){
		var itemsStr = getCookie(cookieName);
		if(itemsStr){
			items = JSON.parse(itemsStr);	
		}else{
			items = [];
		}
	}
}

var cart = (function(){
	var c = new Cart();
	c.load();
	return c;
})();
